package com.jdk.demo.nio.bytebuffer;

import java.nio.ByteBuffer;

public class CompareDemo {
	
	private ByteBuffer thiz;
	
	// 判断两个ByteBuffer的范围是从当前ByteBuffer对象的当前位置开始，以两个ByteBuffer对象最小的remaining值结束，说明判断的范围是remaining的交集
	// 如果在开始与结束的范围之间有一个字节不同，则返回两者的减数
	// 如果在开始与结束的范围之间每个字节都相同，则返回两者的remaining的减数
	// ByeBiuffer的compareTo源码
	public int compareTo(ByteBuffer that){
		int n = thiz.position() + Math.min(thiz.remaining(), that.remaining());
		for(int i=thiz.position(), j=that.position(); i<n; i++, j++){
			int cmp = compare(thiz.get(i), that.get(j));
			if(cmp != 0){
				return cmp;
			}
		}
		return thiz.remaining() - that.remaining();
	}

	private int compare(byte x, byte y) {
		return x - y;
	}
	
	public static void main(String[] args) {
		test1();
		test2();
	}

	// 如果在开始与结束的范围之间有一个字节不同，则返回两者的减数
	private static void test1() {
		byte[] byteArrayIn1 = {3, 4, 5};
		byte[] byteArrayIn2 = {1, 2, 3, 104, 5, 6, 7, 8, 9, 10};
		ByteBuffer bytebuffer1 = ByteBuffer.wrap(byteArrayIn1);
		ByteBuffer bytebuffer2 = ByteBuffer.wrap(byteArrayIn2);
		
		bytebuffer1.position(0);
		bytebuffer2.position(2);
		System.out.println(bytebuffer1.compareTo(bytebuffer2));
	}
	
	// 如果在开始与结束的范围之间每个字节都相同，则返回两者的remaining的减数
	private static void test2() {
		byte[] byteArrayIn1 = {3, 4, 5};
		byte[] byteArrayIn2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		ByteBuffer bytebuffer1 = ByteBuffer.wrap(byteArrayIn1);
		ByteBuffer bytebuffer2 = ByteBuffer.wrap(byteArrayIn2);
		
		bytebuffer1.position(0);
		bytebuffer2.position(2);
		System.out.println(bytebuffer1.compareTo(bytebuffer2));
	}

}
